package com.warmlight.voicepacket.network;

import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.warmlight.voicepacket.BuildConfig;
import com.warmlight.voicepacket.MApplication;
import com.warmlight.voicepacket.common.Constants;
import com.warmlight.voicepacket.network.cookie.CommonCookieJar;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * 网络请求工具类
 * Created by weiweijinpeng on 2017/12/26.
 */
public class CommonHelper {

    private static OkHttpClient mOkHttpClient;

    static {
        initOkHttpClient();
    }

    /**
     * 根据传入的baseUrl，和api创建retrofit
     */
    public static <T> T createApi(Class<T> clazz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(clazz);
    }

    /**
     * 根据传入的baseUrl，和api创建retrofit
     */
    public static <T> T createApi(Class<T> clazz, String baseUrl) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(clazz);
    }

    /**
     * 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器
     */
    private static void initOkHttpClient() {
        if (mOkHttpClient == null) {
            synchronized (CommonHelper.class) {
                if (mOkHttpClient == null) {

                    OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
                    //设置Http缓存
                    Cache cache = new Cache(new File(MApplication.getInstance().getCacheDir(), "HttpCache"), 1024 * 1024 * 10);
                    CommonCookieJar.getInstance().setCookieCache(new SetCookieCache(),new SharedPrefsCookiePersistor(MApplication.getInstance()));
                    if(BuildConfig.DEBUG){
//                        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> {
//                            Log.i("RetrofitLog","retrofitBack = " + message);
//                        });
//                        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                        httpBuilder.cookieJar(CommonCookieJar.getInstance()) //cookie持久化
//                                .addInterceptor(interceptor)
//                                .cache(cache)
//                                .addNetworkInterceptor(new CacheInterceptor())
//                                .addNetworkInterceptor(new StethoInterceptor())
                                .retryOnConnectionFailure(true)
                                .connectTimeout(20000, TimeUnit.SECONDS)
                                .writeTimeout(20000, TimeUnit.SECONDS)
                                .readTimeout(20000, TimeUnit.SECONDS);
                    }else {
                        httpBuilder.cookieJar(CommonCookieJar.getInstance())
//                                .cache(cache)
//                                .addNetworkInterceptor(new CacheInterceptor())
//                                .addNetworkInterceptor(new StethoInterceptor())
                                .retryOnConnectionFailure(true)
                                .connectTimeout(20000, TimeUnit.SECONDS)
                                .writeTimeout(20000, TimeUnit.SECONDS)
                                .readTimeout(20000, TimeUnit.SECONDS);
                    }
                    mOkHttpClient = httpBuilder.build();
                }
            }
        }
    }

//    /**
//     * 为okhttp添加缓存，这里是考虑到服务器不支持缓存时，从而让okhttp支持缓存
//     */
//    private static class CacheInterceptor implements Interceptor {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            // 有网络时 设置缓存超时时间1个小时
//            int maxAge = 60 * 60;
//            // 无网络时，设置超时为1天
//            int maxStale = 60 * 60 * 24;
//            Request request = chain.request();
//            if (CommonUtil.isNetworkAvailable(AppContext.getInstance())) {
//                //有网络时只从网络获取
//                request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
//            } else {
//                //无网络时只从缓存中读取
//                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
//            }
//            Response response = chain.proceed(request);
//            if (CommonUtil.isNetworkAvailable(AppContext.getInstance())) {
//                response = response.newBuilder()
//                        .removeHeader("Pragma")
//                        .header("Cache-Control", "public, max-age=" + maxAge)
//                        .build();
//            } else {
//                response = response.newBuilder()
//                        .removeHeader("Pragma")
//                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
//                        .build();
//            }
//            return response;
//        }
//    }
}
